#import modules
import pygame
from pygame.locals import *
import time
import random
#定义玩具飞机类
class HeroPlane:
	def __init__(self, screen_temp):
		self.x = 200
		self.y = 400
		self.screen = screen_temp
		self.image = pygame.image.load('./images/me.png')
		self.bullet_list = []	#子弹列表

#定义玩家飞机
	def display(self):

		for b in self.bullet_list:
			b.display()
			if b.move():
				self.bullet_list.remove(b)
		self.screen.blit(self.image,(self.x,self.y))

	def move_left(self):
		self.x -= 5
		if self.x <= 0:
			self.x = 0

	def move_right(self):
		self.x += 5
		if self.x >= 406:
			self.x = 406

	def fire(self):
		self.bullet_list.append(Bullet(self.screen,self.x,self.y))
		print(len(self.bullet_list))

#定义子弹类
class Bullet:
	def __init__(self, screen_temp,x,y):
		self.x = x+53
		self.y = y
		self.screen = screen_temp
		self.image = pygame.image.load('./images/pd.png')
#调用子弹
	def display(self):
		self.screen.blit(self.image,(self.x,self.y))
#子弹移动
	def move(self):
		self.y -= 10
		if self.y <= -20:
			return True

#定义敌机类
class EnemyPlane:
	def __init__(self, screen_temp):
		self.x = random.choice(range(408))
		self.y = -75
		self.screen = screen_temp
		self.image = pygame.image.load('./images/e0.png')
#调用敌机
	def display(self):
		self.screen.blit(self.image,(self.x,self.y))
#敌机移动
	def move(self,hero):
		self.y += 4
		#敌机出屏幕
		if self.y > 568:
			return True
		#遍历字典，碰撞检测
		for bo in hero.bullet_list:
			if bo.x>self.x+12 and bo.x<self.x+92 and bo.y>self.y+20 and bo.y<self.y+60:
				hero.bullet_list.remove(bo)
				return True
		#判断是否越界
		if self.y>512:
			return True


#键盘控制函数
def key_control(hero_temp):

	#执行退出操作
	for event in pygame.event.get():
		if event.type == QUIT:
			print('exit()')
			exit()

	#获取键盘信息
	press_keys = pygame.key.get_pressed()
	#print(press_keys)
	#做判断，并执行对象的操作
	if press_keys[K_LEFT] or press_keys[K_a]:
		print('Left...')
		hero_temp.move_left()

	if press_keys[K_RIGHT] or press_keys[K_d]:
		print('Right...')
		hero_temp.move_right()

	if press_keys[K_SPACE]:
		print('Space...')
		hero_temp.fire()


#定义主程序函数
def main():
	'''
	'''
	#创建游戏窗口
	screen = pygame.display.set_mode((512,568),0,0)

	#创建游戏背景
	background = pygame.image.load('./images/bg2.jpg')

	#创建玩家飞机
	hero = HeroPlane(screen)


	m = -968
	enemylist = []	#存放敌机列表
	while True:
		#绘制画面
		screen.blit(background, (0, m))
		m += 2
		if m >= -200:
			m = -968

		#调用玩家飞机
		hero.display()

		#调用键盘事件
		key_control(hero)

		#随机调用敌机
		if random.choice(range(20)) == 5:
			enemylist.append(EnemyPlane(screen))
		#遍历敌机并移动
		for en in enemylist:
			en.display()
			if en.move(hero):
				enemylist.remove(en)

		#更新显示
		pygame.display.update()

		#定时显示
		time.sleep(0.04)

#判断当前是否是主运行程序，并调用

if __name__ == '__main__':
	main()